package cn.qdu.dao;

import cn.qdu.model.Topic;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TopicDao {
    private DataSource dataSource; // 假设已注入数据源

    public List<Topic> getHotTopics(int limit) throws SQLException {
        List<Topic> topics = new ArrayList<>();
        String sql = "SELECT t.topic_id, t.topic_name, " +
                "COUNT(pt.post_id) AS post_count, " +
                "COUNT(pt.post_id) * 10 + " +  // 基础分数
                "SUM(CASE WHEN p.created_at > NOW() - INTERVAL 7 DAY THEN 5 ELSE 1 END) AS hot_score " +
                "FROM topics t " +
                "LEFT JOIN post_topics pt ON t.topic_id = pt.topic_id " +
                "LEFT JOIN posts p ON pt.post_id = p.post_id " +
                "GROUP BY t.topic_id, t.topic_name " +
                "ORDER BY hot_score DESC " +
                "LIMIT ?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, limit);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Topic topic = new Topic(
                            rs.getString("topic_id"),
                            rs.getString("topic_name"),
                            rs.getInt("post_count"),
                            rs.getInt("hot_score")
                    );
                    topics.add(topic);
                }
            }
        }
        return topics;
    }

}